package cn.smartorigin.soas.frame.panel;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.Vector;

import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable.PrintMode;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.table.DefaultTableModel;

import cn.smartorigin.soas.data.SqliteConnecter;
import cn.smartorigin.soas.data.TestData;
import cn.smartorigin.soas.frame.AddClient;
import cn.smartorigin.soas.frame.AddOrder;
import cn.smartorigin.soas.frame.CellComboBox;
import cn.smartorigin.soas.frame.ColorTableIF;
import cn.smartorigin.soas.frame.ImageButton;
import cn.smartorigin.soas.frame.JColorTable;
import cn.smartorigin.soas.frame.MainFrame;

public class OrderPage extends Portlet  implements ColorTableIF{
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private int clientId;
	private String[] TABLE_HEAD = {"ID号","日期", "委加单号" ,"品名", "表面处理方式", "镀种", "单价","数量/kg","总价"};
	private ImageIcon icon_nomal2 = new ImageIcon("res/images/report_form_bg.png");
    private ImageIcon icon_selected2 = new ImageIcon("res/images/report_form_bg_selected.png");
    ImageIcon minimizeIcon = new ImageIcon("res/images/add_order.png");
    ImageIcon minimizeIcon_p = new ImageIcon("res/images/add_order_p.png");
    ImageIcon printIcon = new ImageIcon("res/images/print.png");
    ImageIcon printIcon_p = new ImageIcon("res/images/print_p.png");
    ImageIcon addOrderNumIcon = new ImageIcon("res/images/addOrderNum.png");
    ImageIcon addOrderNumIcon_p = new ImageIcon("res/images/addOrderNum_p.png");
    ImageIcon saveIcon = new ImageIcon("res/images/save.png");
    ImageIcon saveIcon_p = new ImageIcon("res/images/save_p.png");
    ImageIcon cancelIcon = new ImageIcon("res/images/cancel.png");
    ImageIcon cancelIcon_p = new ImageIcon("res/images/cancel_p.png");
    
    JColorTable   cTable;	
    
	ImageButton btn2 = new ImageButton(icon_nomal2, icon_nomal2, icon_selected2);
	ImageButton addOrderNumBtn= new ImageButton(addOrderNumIcon, addOrderNumIcon, addOrderNumIcon_p);
	JComboBox mProductName, mOrderNum;
	CellComboBox mYear , mMonth;
	JLabel mTotalPrice;
	JTextField mQuality;
	boolean input_orderNum_mode;
	JPanel pl_bottom = new JPanel();
	JPanel pl_right = new JPanel();
	JPanel pl_left = new JPanel();
	JPanel orderNumPl ;
	JPanel orderPrdctPl ;
	
	JTextField order_num ;
	JComboBox order_year, order_month, order_day;
	String year_labels[] = { "2009", "2010", "2011", "2012", "2013", "2014" , "2015" , "2016"};
	String month_labels[] = { "1", "2", "3", "4", "5", "6" , "7" , "8", "9", "10", "11", "12"};
	String day_labels[] = {"1", "2", "3", "4", "5", "6" , "7" , "8", "9", "10", 
			"11", "12", "13", "14", "15", "16" , "17" , "18", "19", "20",
			"21", "22", "23", "24", "25", "26" , "27" , "28", "29", "30", "31"};
	int month, year, day ;
	
	public OrderPage(int id){
		this.clientId = id;
		this.setLayout(new BorderLayout());
		this.add(btn2, BorderLayout.CENTER);
		
		Calendar c = Calendar.getInstance();
		month =c.get(Calendar.MONTH);
		year = c.get(Calendar.YEAR);
		day = c.get(Calendar.DATE);
	}

	@Override
	public ImageButton getImageButton() {
		return btn2;
	}

	@Override
	public void showMode(boolean isFullscreen) {
		// TODO Auto-generated method stub
		if(isFullscreen){	
							
			this.removeAll();
			
			// toolbar
	        JToolBar toolbar = super.getControlPanel();
	        toolbar.add(loadTimeSelectModule(), BorderLayout.WEST);
	        
	        
	        // product order list table
			DefaultTableModel model = this.loadClientOrderDate();
			cTable = new JColorTable(model);
		    JScrollPane mClistPanel= new JScrollPane(cTable);

		    flashTotalPrice();
	        
		    this.add(mClistPanel, BorderLayout.CENTER);
		    this.add(mClistPanel, BorderLayout.CENTER);
		    this.add(toolbar, BorderLayout.NORTH);
		    
			//pl.setBackground(Color.white);
		    pl_bottom.setLayout(new BorderLayout());
			pl_right.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 10));
			input_orderNum_mode = false;
			
	        try {
	        	orderNumPl = createOrderNumInputPanel();
				orderPrdctPl = createOrderProductInputPanel();
			} catch (ClassNotFoundException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			} catch (SQLException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}
			
			pl_left.add(showOrderInputModel(input_orderNum_mode));
	
			addOrderNumBtn.addActionListener(new ActionListener(){

				@Override
				public void actionPerformed(ActionEvent e) {
					// TODO Auto-generated method stub
					input_orderNum_mode = true;
					pl_left.remove(orderPrdctPl);
					pl_left.add(showOrderInputModel(input_orderNum_mode));
					OrderPage.this.revalidate();
					OrderPage.this.repaint();
				}
				
			});
			
					
			ImageButton printBtn= new ImageButton(printIcon, printIcon, printIcon_p);
			printBtn.addActionListener(new ActionListener(){

				@Override
				public void actionPerformed(ActionEvent e) {
					// TODO Auto-generated method stub
//				    PrinterJob printJob = PrinterJob.getPrinterJob();
//				    //printJob.setPrintable(OrderPage.this);
//				    if (printJob.printDialog())
//				      try { 
//				        printJob.print();
//				      } catch(PrinterException pe) {
//				        System.out.println("Error printing: " + pe);
//				      }
				      
					try {
						MessageFormat footerFormat = new MessageFormat("Page - {0}");
						MessageFormat headerFormat = new MessageFormat("太仓市锦飞电镀结算清单");
						boolean showPrintDialog = true;
						boolean interactive = true;
						boolean complete = cTable.print(PrintMode.FIT_WIDTH,headerFormat, footerFormat, showPrintDialog, null, interactive, null);
						if (complete) {
							/* show a success message */
							// ...
						} else {
							/*
							 * show a message indicating that printing was
							 * cancelled
							 */
							// ...
						}
					} catch (PrinterException pe) {
						/* Printing failed, report to the user */
						// ...
					}

				}
				
			});
			pl_right.add(printBtn);
			
			pl_bottom.add(pl_right, BorderLayout.EAST);
			pl_bottom.add(pl_left, BorderLayout.WEST);
			this.add(pl_bottom, BorderLayout.SOUTH);
			
		}else{
			pl_left.removeAll();
			pl_right.removeAll();
			this.removeAll();
			this.add(btn2, BorderLayout.CENTER);
		}
	}
	
	private JPanel loadTimeSelectModule(){
		
		JPanel timePanel = new JPanel();
		timePanel.setLayout(new FlowLayout(FlowLayout.CENTER, 20 ,0));
		timePanel.setOpaque(false);
		
    	JLabel jl = new JLabel("订单列表");
		jl.setFont(new Font("宋体", Font.BOLD, 14));
		
		JLabel lbl_year = new JLabel("年");
		//mYear = new JComboBox(year_labels);
		mYear = new CellComboBox(year_labels);
		mYear.setBackground(Color.white);
		mYear.setSelectedIndex(year - 2009);
		mYear.addActionListener(new ActionListener() {
		      public void actionPerformed(ActionEvent e) {
		          //System.out.println("Selected index=" + mYear.getSelectedIndex() + " Selected item=" + mYear.getSelectedItem());
		          flashClientTable();
		        }
		      });
		
		JLabel lbl_month = new JLabel("月");
		//mMonth = new JComboBox(month_labels);
		mMonth = new CellComboBox(month_labels);
		mMonth.setBackground(Color.white);
		mMonth.setSelectedIndex(month);
		mMonth.addActionListener(new ActionListener() {
		      public void actionPerformed(ActionEvent e) {
		          //System.out.println("Selected index=" + mMonth.getSelectedIndex() + " Selected item=" + mMonth.getSelectedItem());
		          flashClientTable();
		        }
		      });
		
		
		JLabel lbl_totalPicce = new JLabel("  当月金额总计：");
		mTotalPrice = new JLabel();

		
		timePanel.add(jl);
		timePanel.add(mYear);
		timePanel.add(lbl_year);
		timePanel.add(mMonth);
		timePanel.add(lbl_month);
		timePanel.add(lbl_totalPicce);
		timePanel.add(mTotalPrice);

		
		return timePanel;
	}
	
	private void flashClientTable(){
		DefaultTableModel model = loadClientOrderDate();
		cTable.setModel(model);
	    flashTotalPrice();
	}
	
	/**
	 * loader client order data by month
	 * @return the data table model
	 */
	private DefaultTableModel loadClientOrderDate(){
		DefaultTableModel model = new DefaultTableModel();
		for(int i=0; i<TABLE_HEAD.length; i++){
			model.addColumn(TABLE_HEAD[i]);
		}
	    try {
			TestData.getSelectUsrTblOrderData(new SqliteConnecter(), model, clientId, mMonth.getSelectedItem().toString());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}	
	   return model;
	   
	}
	
	/**
	 * Order input model
	 * @param flag
	 * @return
	 */
	private JPanel showOrderInputModel(boolean flag){

		if(flag){
			return orderNumPl;
		}else{
			return orderPrdctPl;
		}
	}
	
	
	
	/**
	 * create a panel for input product
	 * @return
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	private JPanel createOrderProductInputPanel()throws ClassNotFoundException, SQLException{
		JPanel jp = new JPanel();
		jp.setLayout(new FlowLayout(FlowLayout.LEFT, 5 ,5));
		
		JLabel orderNumlbl  = new JLabel("委加单号：");
		Vector v =  TestData.queryDeliveryListByMonth(new SqliteConnecter(), clientId, mMonth.getSelectedItem().toString());
		mOrderNum = new JComboBox(v);
		//mOrderNum.setPreferredSize( new Dimension(200, 20));
		mOrderNum.setBackground(Color.white);
		
		JLabel productNamelbl  = new JLabel("  品名：");
		mProductName = new JComboBox(TestData.queryProductList(new SqliteConnecter(), clientId));
		//mProductName.setPreferredSize(new Dimension(200, 20));
		mProductName.setBackground(Color.white);
		
		JLabel qualitylbl  = new JLabel("  数量/KG：");
		mQuality = new JTextField();
		mQuality.setPreferredSize(new Dimension(100, 25));
		mQuality.setBackground(Color.white);
		
        ImageButton addOrderPrdct = new ImageButton(minimizeIcon, minimizeIcon, minimizeIcon_p);
        addOrderPrdct.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				//new AddOrder();
				String productName = mProductName.getSelectedItem().toString();
				String quality = mQuality.getText();
				String deliveryNum = mOrderNum.getSelectedItem().toString();
				int err;
				
				/**
				 * 保存数据
				 */
				if(productName.isEmpty() ||deliveryNum.isEmpty() || quality.isEmpty()){
					JOptionPane.showMessageDialog(null, "表格填写错误, 不能为空 ！", "警告", JOptionPane.WARNING_MESSAGE);
				}else{
					try {
						TestData.insertOrder(new SqliteConnecter(), clientId, productName, deliveryNum, quality);
					} catch (ClassNotFoundException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (SQLException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					mQuality.setText("");
					flashClientTable();
	//				flashOrderNum();
					repaint();
				}
				
			}
        	
        });
        
		jp.add(addOrderNumBtn);
		jp.add(orderNumlbl);
		jp.add(mOrderNum);
		jp.add(productNamelbl);
		jp.add(mProductName);
		jp.add(qualitylbl);
		jp.add(mQuality);
        jp.add(addOrderPrdct);
		
		return jp;
	}
	
	/*
	 * create a panel for input order number
	 */
	private JPanel createOrderNumInputPanel(){
		JPanel jp = new JPanel();
		jp.setLayout(new FlowLayout(FlowLayout.LEFT, 5 ,5));
		
		JLabel order_num_lbl  = new JLabel("订单号：");
		JLabel order_year_lbl   = new JLabel("  年：");
		JLabel order_month_lbl   = new JLabel("  月：");
		JLabel order_day_lbl   = new JLabel("  日：");
		
		order_num = new JTextField();
		order_num.setPreferredSize(new Dimension(100, 25));
		
		order_year = new JComboBox(this.year_labels);
		order_year.setSelectedIndex(year-2009);
		order_year.setBackground(Color.white);
		
		order_month = new JComboBox(this.month_labels);
		order_month.setSelectedIndex(month);
		order_month.setBackground(Color.white);
		
		order_day = new JComboBox(this.day_labels);
		order_day.setSelectedIndex(day-1);
		order_day.setBackground(Color.white);
		
        ImageButton save = new ImageButton(saveIcon, saveIcon, saveIcon_p);
        save.addActionListener(new ActionListener(){
        	@Override
			public void actionPerformed(ActionEvent e) {
        		int err;
        		String od_num, od_year, od_month, od_day;
        		od_num = order_num.getText();
        		od_year = order_year.getSelectedItem().toString();
        		od_month = order_month.getSelectedItem().toString();
        		od_day = order_day.getSelectedItem().toString();
        		
        		if(od_num.isEmpty()==true || od_year.isEmpty()==true|| od_month.isEmpty()==true|| od_day.isEmpty()==true){
        			JOptionPane.showMessageDialog(null, "表格填写错误, 不能为空 ！", "警告", JOptionPane.WARNING_MESSAGE);
        		}else{
        			try {
						err = TestData.insertOrderNum(new SqliteConnecter(), clientId, od_num, od_year, od_month, od_day);
						if(err > 0){
							JOptionPane.showMessageDialog(null, "委加单号已经存在，不能重复 ！", "警告", JOptionPane.WARNING_MESSAGE);
							return ;
						}
						showProductInputMode();
					} catch (ClassNotFoundException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (SQLException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
        		}
        	}
        });
        
        ImageButton cancel = new ImageButton(cancelIcon, cancelIcon, cancelIcon_p);
        cancel.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				order_num.setText(null);
				input_orderNum_mode = false;
				pl_left.remove(orderNumPl);
				pl_left.add(showOrderInputModel(input_orderNum_mode));
				OrderPage.this.revalidate();
				OrderPage.this.repaint();
			}
        	
        });
		

		jp.add(order_num_lbl);
		jp.add(order_num);
		jp.add(order_year_lbl);
		jp.add(order_year);
		jp.add(order_month_lbl);
		jp.add(order_month);
		jp.add(order_day_lbl);
		jp.add(order_day);
		
		jp.add(save);
		jp.add(cancel);
		
		return jp;
	}
	
	
	/**
	 * 刷新订单号
	 */
	private void flashOrderNum(){
		try {
			//mOrderNum = new JComboBox(TestData.queryDeliveryList(new SqliteConnecter(), clientId));
			Vector v =  TestData.queryDeliveryListByMonth(new SqliteConnecter(), clientId, mMonth.getSelectedItem().toString());
			DefaultComboBoxModel model =  new DefaultComboBoxModel();
			for(int i=0;i <v.size(); i++){
				model.addElement(v.get(i).toString());
			}
				
			mOrderNum.setModel(model);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 产品输入模式
	 */
	private void showProductInputMode(){
		order_num.setText(null);
		input_orderNum_mode = false;
		pl_left.remove(orderNumPl);
		pl_left.add(showOrderInputModel(input_orderNum_mode));
		flashOrderNum();
		OrderPage.this.revalidate();
		OrderPage.this.repaint();
	}

	@Override
	public void TableModify(int rowId) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void TableDelete(int rowId) {
		// TODO Auto-generated method stub
		String str1 =  (String) cTable.getValueAt(rowId, 0).toString();
		int productId = Integer.parseInt(str1);
		try {
			TestData.deleteOrderProduct(new SqliteConnecter(), productId);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		//showMode(true);
		flashOrderProductTable();
//		this.revalidate();	// 更新容器本身
		this.repaint();		// 重绘
	}
	
	/**
	 * Flash Product data Table
	 */
	private void flashOrderProductTable(){
		DefaultTableModel model = this.loadClientOrderDate();
		cTable.removeAll();
		cTable.setModel(model);
	}
	 
	/**
	 * 刷新总价
	 */
	private void flashTotalPrice(){
	    float value = 0; 
	    int colCount = cTable.getColumnCount();
	    for(int i=0; i<cTable.getRowCount(); i++){
	    	String str = cTable.getValueAt(i, colCount-1).toString();
	    	value += Float.parseFloat(str);
//	    	System.out.println(value);
	    }
	    mTotalPrice.setText(Float.toString(value)+ " 元");
	}

}
